package com.example.testssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author liang zai
 * @date 2022/4/12 18:14
 * @description
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @ResponseBody
    @GetMapping("userInfo")
    public String userInfo(@RequestParam("token")String token){
        String username = redisTemplate.opsForValue().get(token);
        if (StringUtils.hasText(username)){
            //
            return username;
        }
        return "";
    }


    @GetMapping("/login.html")
    public String doLogin(@RequestParam("redirect_url")String url, Model model,
                          @CookieValue(value = "sso_cookie",required = false) String sso_token){
        if (StringUtils.hasText(sso_token)){
            //如果有cookie并且不为空，说明之前有人登录过了，浏览器留下了痕迹，直接可以免登录
            return "redirect:" + url + "?token=" + sso_token;

        }
        //登录成功跳转
        model.addAttribute("url",url);
        return "login";
    }
    @PostMapping("toLogin")
    public String toLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String url,
                          HttpServletResponse response){
        if (StringUtils.hasText(username) && StringUtils.hasText(password)){
            //登录成功

            String uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(uuid,username);
            //登录成功后给浏览器带一个cookie
            Cookie cookie = new Cookie("sso_cookie",uuid);
            response.addCookie(cookie);
            return "redirect:" + url + "?token=" + uuid;
        }
        return "login";
    }
}
